package com.hulk.dryad.manage.framework.operlog;

import cn.hutool.core.util.StrUtil;
import com.hulk.dryad.manage.framework.datasource.DynamicDataSourceHolder;
import com.hulk.dryad.persistence.entity.SysOperLog;
import com.hulk.dryad.manage.provider.service.SysOperLogService;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.ip2region.core.Ip2regionSearcher;
import net.dreamlu.mica.ip2region.core.IpInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;

import java.time.LocalDateTime;

/**
 * 监听系统日志事件，系统日志入库
 *
 * @author hulk
 */
@Slf4j
@RequiredArgsConstructor
public class OperLogListener {


	private final   Ip2regionSearcher searcher;

	private final   SysOperLogService logService;

	@Async
	@Order
	@EventListener(OperLogEvent.class)
	public void saveSysLog(OperLogEvent event) {

        DynamicDataSourceHolder.set(event.getTenantId());
		SysOperLog operLog = new SysOperLog();
		BeanUtils.copyProperties(event, operLog);
		// 获取操作系统和浏览器信息
		UserAgent userAgent = UserAgent.parseUserAgentString(event.getUserAgent());
		OperatingSystem system = userAgent.getOperatingSystem();
		operLog.setOs(system.getName());
		Browser browser = userAgent.getBrowser();
		operLog.setBrowser(browser.getName());
		operLog.setCreatedTime(LocalDateTime.now());
		operLog.setUpdatedTime(LocalDateTime.now());
		String requestIp = event.getRequestIp();
		// 如果 ip 为空直接保存
		if (StrUtil.isNotBlank(requestIp)) {
			// ip 不为空，查找 ip 的地理信息
			IpInfo ipInfo = searcher.memorySearch(requestIp);
			if (ipInfo != null) {
				operLog.setAddress(ipInfo.getAddress());
			}
		}

		log.info(operLog.toString());
		logService.save(operLog);
	}
}
